package Model.DbAccess;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DbConnection {
	private String serverURL = "localhost";
	private int port = 1433;
	private String dbName = "PHONESHOP";
	private String username = "sa";
	private String pwd = "123123";
	private Connection con;
	
	public void makeConnection() {
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			con = DriverManager.getConnection("jdbc:sqlserver://"+serverURL+":"+port+";databaseName="+dbName, username, pwd);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public ResultSet executeQuery(String sql) {
		try {
			PreparedStatement ps = con.prepareStatement(sql);
			return ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public ResultSet executeQuery(String sql, Object[] params) {
		try {
			PreparedStatement ps = con.prepareStatement(sql);
			for(int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
			return ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public boolean executeUpdate(String sql, Object[] params) {
		int r = -1;
		
		try {
			PreparedStatement ps = con.prepareStatement(sql);
			for(int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
			r = ps.executeUpdate();
			
			if(r>0) {
				return true;
			}			
		} catch (SQLException e) {
			return false;
		}
		return false;
	}
	
	public void closeConnection() {
		try {
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
